package com.example.controller;

import com.example.dao.DepartmentDAO;
import com.example.dao.EmployeeDAO;
import com.example.model.Department;
import com.example.model.Employee;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

import java.util.List;

@WebServlet(name = "EmployeeServlet", value = {
        "/employees", "/addEmployee", "/editEmployee", "/updateEmployee", "/deleteEmployee"
})
public class EmployeeServlet extends HttpServlet {
    private EmployeeDAO employeeDAO;
    private DepartmentDAO departmentDAO;
    private static final int RECORDS_PER_PAGE = 5;

    @Override
    public void init() {
        employeeDAO = new EmployeeDAO();
        departmentDAO = new DepartmentDAO();
    }
    private boolean isAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        return session != null && "admin".equals(session.getAttribute("role"));
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (!isAdmin(request)) {
            response.sendRedirect("login.jsp");
            return;
        }
        String action = request.getServletPath();

        if ("/addEmployee".equals(action)) {
            addEmployee(request, response);
        } else if ("/updateEmployee".equals(action)) {
            updateEmployee(request, response);
        } else if ("/deleteEmployee".equals(action)) {
            deleteEmployee(request, response);
        } else {
            response.sendRedirect("employees");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (!isAdmin(request)) {
            response.sendRedirect("login.jsp");
            return;
        }
        String action = request.getServletPath();

        if ("/employees".equals(action)) {
            listEmployees(request, response);
        } else if ("/addEmployee".equals(action)) {
            showAddForm(request, response);
        } else if ("/editEmployee".equals(action)) {
            showEditForm(request, response);
        } else if ("/deleteEmployee".equals(action)) {
            deleteEmployee(request, response);
        } else {
            response.sendRedirect("employees");
        }
    }

    private void listEmployees(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取当前页码，默认为第一页
            int page = 1;
            String pageParam = request.getParameter("page");
            if (pageParam != null && !pageParam.isEmpty()) {
                page = Integer.parseInt(pageParam);
            }

            // 获取员工总数
            int totalEmployees = employeeDAO.getTotalEmployees();
            int totalPages = (int) Math.ceil((double) totalEmployees / RECORDS_PER_PAGE);

            // 设置请求属性
            request.setAttribute("employees", employeeDAO.getAllEmployees(page, RECORDS_PER_PAGE));
            request.setAttribute("currentPage", page);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("totalEmployees", totalEmployees);

            // 转发到列表页面
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/listEmployees.jsp");
            dispatcher.forward(request, response);
        } catch (Exception e) {
            throw new ServletException("Error listing employees", e);
        }
    }

    private void showAddForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            List<Department> departments = departmentDAO.getAllDepartments();
            request.setAttribute("departments", departments);
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/addEmployee.jsp");
            dispatcher.forward(request, response);
        } catch (Exception e) {
            throw new ServletException("Error showing add form", e);
        }
    }

    private void addEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Employee emp = new Employee();
        emp.setName(request.getParameter("name"));
        emp.setGender(request.getParameter("gender"));
        emp.setAge(Integer.parseInt(request.getParameter("age")));
        emp.setDeptId(Integer.parseInt(request.getParameter("deptId")));
        emp.setPosition(request.getParameter("position"));


        try {
            employeeDAO.addEmployee(emp);
            // 添加成功后重定向到员工列表
            response.sendRedirect("employees");
        } catch (Exception e) {
            throw new ServletException("Error adding employee", e);
        }
    }
    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            int id = Integer.parseInt(request.getParameter("id"));
            Employee employee = employeeDAO.getEmployeeById(id);
            List<Department> departments = departmentDAO.getAllDepartments();

            if (employee != null) {
                request.setAttribute("employee", employee);
                request.setAttribute("departments", departments);
                RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/editEmployee.jsp");
                dispatcher.forward(request, response);
            } else {
                response.sendRedirect("employees");
            }
        } catch (Exception e) {
            throw new ServletException("Error showing edit form", e);
        }
    }

    private void updateEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Employee emp = new Employee();
        emp.setId(Integer.parseInt(request.getParameter("id")));
        emp.setName(request.getParameter("name"));
        emp.setGender(request.getParameter("gender"));
        emp.setAge(Integer.parseInt(request.getParameter("age")));
        emp.setDeptId(Integer.parseInt(request.getParameter("deptId")));
        emp.setPosition(request.getParameter("position"));


        try {
            employeeDAO.updateEmployee(emp);
            response.sendRedirect("employees");
        } catch (Exception e) {
            throw new ServletException("Error updating employee", e);
        }
    }

    private void deleteEmployee(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        try {
            employeeDAO.deleteEmployee(id);
            response.sendRedirect("employees");
        } catch (Exception e) {
            throw new ServletException("Error deleting employee", e);
        }
    }
}